package com.hou.netty.serial;

import com.hou.netty.TestSystem.GzipUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;
import java.io.FileInputStream;

public class Client {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //设置Marshalling编解码
                            socketChannel.pipeline().addLast(MarshallingCodeFactory.createMarshallingDecoder());
                            socketChannel.pipeline().addLast(MarshallingCodeFactory.createMarshallingEncoder());
                            socketChannel.pipeline().addLast(new ClientHandler());//客户端业务处理
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9527).sync();
            //发送数据\
            Order order = new Order();
            order.setName("衣服");
            order.setPrice(88.88);
            //System.getProperty("user.dir"): 当前程序所在目录,   File.separatorChar: 文件分隔符
            String path = System.getProperty("user.dir") + File.separatorChar + "resources" + File.separatorChar + "001.jpg";
            File file = new File(path);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];//available:获取流中可读取的数据大小
            inputStream.read(bytes);//将文件流转化为byte字节数组
            inputStream.close();
            System.out.println(bytes.length);
            order.setPicture(GzipUtils.gzip(bytes));//压缩byte数组
            channelFuture.channel().writeAndFlush(order);//发送(订单对象)
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
